library(ggplot2)
library(dplyr)
library(modelsummary)
library(kableExtra)
library(stringr)
library(fixest)
library(stargazer)
library(gridExtra)
library(flextable)
library(Hmisc)
library(tidyr)

# load data
df <- readRDS("data/df_long.rds") %>% 
  ungroup() %>% 
  select(meta_UUID, 
         party_01_closest, 
         party_02_closest_party,
         party_03_slightly_closer,
         party_04_voted,
         party_affil) %>% 
  .[!duplicated(.), ]
  
############### Column Names ##############

# party_affil: 
# If closest party indicate -> party_02_closest_party
# else party_03_slightly_closter
# If party_affil still empty (or "No") -> party_04_voted

df <- df %>% 
  mutate(party_affil = ifelse(party_01_closest == "Yes", 
                              party_02_closest_party, NA),
         party_affil = ifelse(is.na(party_affil) & !is.na(party_03_slightly_closer), 
                              party_03_slightly_closer, party_affil),
         d_affil_leaners = ifelse(!is.na(party_affil) & party_affil != "" & party_affil != "No", 
                                1, 0), 
         d_affil_voted = ifelse(is.na(party_affil) | party_affil == "" | party_affil == "No", 
                              1, 0), 
         d_affil_check = d_affil_voted + d_affil_leaners)

df$party_affil <- recode(df$party_affil, 
                         "Synaspismós Rizospastikís Aristerás – Proodeftikí Symmachía (SYRIZA)" = 
                           "SYRIZA")

affil_dummies = df %>% select(meta_UUID, d_affil_voted, d_affil_leaners)


df_wide <- readRDS("data/df_wide.rds")

affil_dummies = df_wide %>% left_join(affil_dummies) %>% 
  select(meta_UUID, d_affil_voted, d_affil_leaners, d_affiliated) %>% 
  mutate(d_affil_voted = ifelse(d_affil_voted == 1 & d_affiliated == 0, 
                                0, d_affil_voted))

df = df_wide %>% left_join(affil_dummies) %>%
  group_by(dem_country_code) %>%
  summarise(sum_leaners = sum(d_affil_leaners, na.rm = T), 
            sum_voted = sum(d_affil_voted, na.rm = T), 
            sum_excluded = sum(1 - d_affiliated), 
            sums = sum_leaners + sum_voted + sum_excluded) %>% 
  mutate(perc_leaners = round(sum_leaners / sums, 3),
         perc_voted = round(sum_voted / sums, 3),
         perc_excluded = round(sum_excluded / sums, 3 ))

df_table = data.frame(country = df$dem_country_code, 
                      N = df$sums, 
                      leaners = paste0(df$sum_leaners, " (", df$perc_leaners*100, "%)"),
                      voters = paste0(df$sum_voted, " (", df$perc_voted*100, "%)"), 
                      excluded = paste0(df$sum_excluded, " (", df$perc_excluded*100, "%)"))

stargazer(df_table, summary =F, type = "html", out = "tables/TableA3.html", rownames = F, digits = 1)
  